package com.yb.guigu.pick.security.config;

import com.yb.guigu.pick.security.bean.WhiteListProperties;
import com.yb.guigu.pick.security.generator.AccessTokenGenerator;
import com.yb.guigu.pick.security.generator.GuiguPickAccessTokenGenerator;
import com.yb.guigu.pick.security.matcher.PermitAllRequestMatcher;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.security.web.access.intercept.RequestMatcherDelegatingAuthorizationManager;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/31 20:00
 * FileName: AppConfig
 * Description:
 */

@Configuration
@ComponentScan(basePackages = {
        "com.yb.guigu.pick.security.generator"
        ,"com.yb.guigu.pick.security.encoder"})
public class AppConfig {

    @Bean
    @ConditionalOnMissingBean
    public AccessTokenGenerator accessTokenGenerator(){
        return new GuiguPickAccessTokenGenerator();
    }


    @Bean
    @ConditionalOnMissingBean
    public PermitAllRequestMatcher permitAllRequestMatcher(WhiteListProperties whiteListProperties){
        return new PermitAllRequestMatcher(whiteListProperties);
    }

    @Bean
    AuthorizationManager<RequestAuthorizationContext> requestMatcherAuthorizationManager(PermitAllRequestMatcher permitAllRequestMatcher) {
        RequestMatcher any = AnyRequestMatcher.INSTANCE;
        AuthorizationManager<HttpServletRequest> manager = RequestMatcherDelegatingAuthorizationManager.builder()
                .add(permitAllRequestMatcher, (authenticationSupplier,requestAuthorizationContext) -> new AuthorizationDecision(true))
                .add(any, AuthenticatedAuthorizationManager.authenticated())
                .build();
        return (authentication, requestAuthorizationContext) -> manager.check(authentication,requestAuthorizationContext.getRequest());
    }
}
